package com.tanxiaoyao.wecon.ui;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.tanxiaoyao.wecon.R;
import com.tanxiaoyao.wecon.app.AppManager;
import com.tanxiaoyao.wecon.net.GlobalConnectHelper;

/**
 * 按键手柄界面
 * 
 * @author tanxiaoyao (junlidev@gmail.com)
 * @version 2014/8/28 21:29.
 */
public class ActivityHandle extends Activity {

	// DEBUG标志
	private static final String TAG = "tanxiaoyao-handle";
	private static final Boolean ISDEBUG = false;
	// 按钮控件
	private FrameLayout positionKeyboard;
	private Button resetBtn;
	private Button selectBtn;
	private FrameLayout modeKeyboard;
	private RelativeLayout handleTouchArea;
	private ScrollView handle_text_area;
	private TextView kb_log_text;
	// 获取控件大小标志位
	private boolean hasGet = false;
	// 全局发送器
	private GlobalConnectHelper globalConnectHelper;
	// 信息字符串
	private static final String KB_RESET = "keyboard_reset_btn";
	private static final String KB_SELECT = "keyboard_select_btn";
	private static final String KB_POS_FRONT = "keyboard_pos_front";
	private static final String KB_POS_RIGHT = "keyboard_pos_right";
	private static final String KB_POS_BACK = "keyboard_pos_back";
	private static final String KB_POS_LEFT = "keyboard_pos_left";
	private static final String KB_POS_FRONT_RIGHT = "keyboard_pos_front_right";
	private static final String KB_POS_RIGHT_BACK = "keyboard_pos_right_back";
	private static final String KB_POS_BACK_LEFT = "keyboard_pos_back_left";
	private static final String KB_POS_LEFT_FRONT = "keyboard_pos_left_front";
	private static final String UP = "_up";
	private static final String DOWN = "_down";
	private static final String KB_MODE_A = "keyboard_mode_a";
	private static final String KB_MODE_B = "keyboard_mode_b";
	private static final String KB_MODE_X = "keyboard_mode_x";
	private static final String KB_MODE_Y = "keyboard_mode_y";

	// 控件坐标
	private int[] posPadPosition = { 0, 0 };
	private int[] modePadPosition = { 0, 0 };
	private float middlePos;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_handle);
		// 取得按钮
		positionKeyboard = (FrameLayout) findViewById(R.id.keyboard_position);
		resetBtn = (Button) findViewById(R.id.btn_keyboard_reset);
		selectBtn = (Button) findViewById(R.id.btn_keyboard_select);
		modeKeyboard = (FrameLayout) findViewById(R.id.keyboard_mode);
		kb_log_text = (TextView) findViewById(R.id.kb_log_text);
		handle_text_area = (ScrollView) findViewById(R.id.handle_text_area);
		// 监听文本改变并自动滚动到底部
		kb_log_text.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				// 设置自动滚到底部
				handle_text_area.post(new Runnable() {
					@Override
					public void run() {
						handle_text_area.fullScroll(ScrollView.FOCUS_DOWN);
					}
				});

			}
		});
		;
		// TODO handleTouchArea
		handleTouchArea = (RelativeLayout) findViewById(R.id.handle_touch_area);
		// 初始化全局发送器
		globalConnectHelper = GlobalConnectHelper.getGlobalConnector();
		// 绑定按钮监器
		resetBtn.setOnClickListener(keyboardOnClickListener);
		selectBtn.setOnClickListener(keyboardOnClickListener);
		handleTouchArea.setOnTouchListener(touchAreaListener);

		super.onCreate(savedInstanceState);
		// Activity压栈
		AppManager.getAppManager().addActivity(this);
	}

	/**
	 * 取得控件屏幕坐标
	 */
	private void getPosition() {
		// 取得控件顶点坐标(注意：这里使用了全屏幕，所以getLocationInWindow与getLocationOnScreen获取的坐标一样)
		// 同理，后面点击事件的getX与getRawX也一样
		positionKeyboard.getLocationInWindow(posPadPosition);
		modeKeyboard.getLocationInWindow(modePadPosition);
		// 计算控件中心坐标
		posPadPosition[0] += (positionKeyboard.getWidth() / 2);
		posPadPosition[1] += (positionKeyboard.getHeight() / 2);
		modePadPosition[0] += (modeKeyboard.getWidth() / 2);
		modePadPosition[1] += (modeKeyboard.getHeight() / 2);
		// 计算两个控件的中心位置
		middlePos = (posPadPosition[0] + modePadPosition[0]) / 2;
	}

	/**
	 * 发送按键消息
	 * 
	 * @param handleCmd
	 *            按键消息
	 * @param event
	 *            按键事件
	 */
	private void send_handle_message(String handleCmd, MotionEvent event) {
		// 发送指令
		globalConnectHelper.sendMess(handleCmd
				+ (event.getAction() == MotionEvent.ACTION_UP ? UP : DOWN));
		// 更新文本区
		if (globalConnectHelper.canSend) {
			kb_log_text.append(handleCmd
					+ (event.getAction() == MotionEvent.ACTION_UP ? UP : DOWN)
					+ "\n");
		}
	}

	/**
	 * 全局界面触摸监听
	 */
	OnTouchListener touchAreaListener = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {

			// 取得控件坐标
			if (!hasGet) {
				getPosition();
				hasGet = true;
			}

			int pointerCount = event.getPointerCount();
			if (pointerCount == 1) {
				// 判断应该触发哪个控件
				if (event.getX() - middlePos > 0) { // 在右边，触发功能区
					modePadOnTouchHandle(event, event.getX()
							- modePadPosition[0],
							-(event.getY() - modePadPosition[1]));
				} else {
					posPadOnTouchHandle(event,
							event.getX() - posPadPosition[0],
							-(event.getY() - posPadPosition[1]));
				}
			} else if (pointerCount == 2) {
				// 分别判断两个点该触发哪个控件
				if (event.getAction() == MotionEvent.ACTION_MOVE
						|| event.getAction() == MotionEvent.ACTION_POINTER_1_DOWN
						|| event.getAction() == MotionEvent.ACTION_POINTER_1_UP
						|| event.getAction() == MotionEvent.ACTION_POINTER_2_DOWN
						|| event.getAction() == MotionEvent.ACTION_POINTER_2_UP) {
					if (event.getX(0) - middlePos > 0) { // 第一个点触发功能区
						modePadOnTouchHandle(event, event.getX(0)
								- modePadPosition[0],
								-(event.getY(0) - modePadPosition[1]));
					} else {
						posPadOnTouchHandle(event, event.getX(0)
								- posPadPosition[0],
								-(event.getY(0) - posPadPosition[1]));
					}
					if (event.getX(1) - middlePos > 0) { // 第二个点触发功能区
						modePadOnTouchHandle(event, event.getX(1)
								- modePadPosition[0],
								-(event.getY(1) - modePadPosition[1]));
					} else {
						posPadOnTouchHandle(event, event.getX(1)
								- posPadPosition[0],
								-(event.getY(1) - posPadPosition[1]));
					}
				}
			}

			return true;
		}
	};

	/**
	 * 功能键触发相应函数
	 * 
	 * @param event
	 *            动作事件
	 * @param posX
	 *            触发点横坐标与控件中心差量（注意这里是绝对坐标系）
	 * @param posY
	 *            出发点纵坐标与控件中心差量
	 */
	private void modePadOnTouchHandle(MotionEvent event, float posX, float posY) {
		// 直接发送对应事件
		// 计算方位
		if (posX >= 0) { // 左半边
			if (posY / posX > 1) {
				send_handle_message(KB_MODE_B, event);
			} else if (posY / posX > -1) {
				send_handle_message(KB_MODE_Y, event);
			} else {
				send_handle_message(KB_MODE_X, event);
			}
		} else {
			if (posY / posX > 1) {
				send_handle_message(KB_MODE_X, event);
			} else if (posY / posX > -1) {
				send_handle_message(KB_MODE_A, event);
			} else {
				send_handle_message(KB_MODE_B, event);
			}
		}
	}

	/**
	 * 方向键触发相应函数
	 * 
	 * @param event
	 *            动作事件
	 * @param posX
	 *            触发点横坐标与控件中心差量（注意这里是绝对坐标系）
	 * @param posY
	 *            出发点纵坐标与控件中心差量
	 */
	private void posPadOnTouchHandle(MotionEvent event, float posX, float posY) {
		// 直接发送对应事件
		// 计算方位
		if (posX >= 0) { // 左半边
			if (posY / posX > 2.414) {
				send_handle_message(KB_POS_FRONT, event);
			} else if (posY / posX > 0.414) {
				send_handle_message(KB_POS_FRONT_RIGHT, event);
			} else if (posY / posX > -0.414) {
				send_handle_message(KB_POS_RIGHT, event);
			} else if (posY / posX > -2.414) {
				send_handle_message(KB_POS_RIGHT_BACK, event);
			} else {
				send_handle_message(KB_POS_BACK, event);
			}
		} else { // 右半边
			if (posY / posX > 2.414) {
				send_handle_message(KB_POS_BACK, event);
			} else if (posY / posX > 0.414) {
				send_handle_message(KB_POS_BACK_LEFT, event);
			} else if (posY / posX > -0.414) {
				send_handle_message(KB_POS_LEFT, event);
			} else if (posY / posX > -2.414) {
				send_handle_message(KB_POS_LEFT_FRONT, event);
			} else {
				send_handle_message(KB_POS_FRONT, event);
			}
		}
	}

	/**
	 * 界面按键监听器
	 */
	OnClickListener keyboardOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btn_keyboard_reset:
				globalConnectHelper.sendMess(KB_RESET);
				break;
			case R.id.btn_keyboard_select:
				globalConnectHelper.sendMess(KB_SELECT);
				break;

			default:
				break;
			}

		}
	};
}
